package com.oa.om.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.audit.log.client.annotation.AuditLog;
import com.mdp.audit.log.client.annotation.OperType;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.om.entity.OmAppliancePurchase;
import com.oa.om.entity.OmApplianceStorage;
import com.oa.om.service.OmAppliancePurchaseService;
import com.oa.om.service.OmApplianceService;
import com.oa.om.service.OmApplianceStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/**/oa/om/omAppliancePurchase")
@Api(tags = {"办公用品采购表-操作接口"})
public class OmAppliancePurchaseController {

    static Logger logger = LoggerFactory.getLogger(OmAppliancePurchaseController.class);

    @Autowired
    private OmAppliancePurchaseService omAppliancePurchaseService;

    @Autowired
    private OmApplianceStorageService omApplianceStorageService;

    @Autowired
    private OmApplianceService omApplianceService;

    @ApiOperation(value = "办公用品采购表-查询列表", notes = " ")
    @ApiEntityParams(OmAppliancePurchase.class)
    @ApiResponses({@ApiResponse(code = 200, response = OmAppliancePurchase.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listOmAppliancePurchase(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "ids");
        QueryWrapper<OmAppliancePurchase> qw = QueryTools.initQueryWrapper(OmAppliancePurchase.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = omAppliancePurchaseService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }


    @ApiOperation(value = "办公用品采购表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = OmAppliancePurchase.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addOmAppliancePurchase(@RequestBody OmAppliancePurchase omAppliancePurchase) {
        if (StringUtils.isEmpty(omAppliancePurchase.getId())) {
            omAppliancePurchase.setId(omAppliancePurchaseService.createKey("id"));
        } else {
            OmAppliancePurchase omAppliancePurchaseQuery = new OmAppliancePurchase(omAppliancePurchase.getId());
            if (omAppliancePurchaseService.countByWhere(omAppliancePurchaseQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        omAppliancePurchase.setCreateTime(new Date());
        omAppliancePurchaseService.insert(omAppliancePurchase);
        return Result.ok("add-ok", "添加成功！").setData(omAppliancePurchase);
    }

    @ApiOperation(value = "办公用品采购表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delOmAppliancePurchase(@RequestBody OmAppliancePurchase omAppliancePurchase) {
        Map<String, Object> m = new HashMap<>();
        omAppliancePurchaseService.deleteByPk(omAppliancePurchase);
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "办公用品采购表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = OmAppliancePurchase.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editOmAppliancePurchase(@RequestBody OmAppliancePurchase omAppliancePurchase) {
        omAppliancePurchaseService.updateById(omAppliancePurchase);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ApiOperation(value = "入库办公用品", notes = "pushOmAppliancePurchase")
    @ApiResponses({@ApiResponse(code = 200, response = OmAppliancePurchase.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/pushStorage", method = RequestMethod.POST)
    @Transactional
    public Result pushStorageOmAppliancePurchase(@RequestBody OmAppliancePurchase omAppliancePurchase) {
        omAppliancePurchase.setIsStorage("3"); //设置为入库状态
        omAppliancePurchaseService.updateByPk(omAppliancePurchase);  //更新采购表的数据
        OmApplianceStorage omApplianceStorage = new OmApplianceStorage();
        BeanUtils.copyProperties(omAppliancePurchase, omApplianceStorage);
        omApplianceStorage.setCreateTime(new Date());
        if (StringUtils.isEmpty(omApplianceStorage.getId())) {
            omApplianceStorage.setId(omApplianceStorageService.createKey("id"));
        } else {
            OmApplianceStorage omApplianceStorageQuery = new OmApplianceStorage(omApplianceStorage.getId());
            if (omApplianceStorageService.countByWhere(omApplianceStorageQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        omApplianceStorageService.insert(omApplianceStorage);  //添加到入库记录表
        omApplianceService.updateStockByRequireComplete(omApplianceStorage.getApplianceId(), omApplianceStorage.getNum());
        return Result.ok().setData(omAppliancePurchase);
    }

    @ApiOperation(value = "批量入库办公用品", notes = "pushOmAppliancePurchase")
    @ApiResponses({@ApiResponse(code = 200, response = OmAppliancePurchase.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/batPushStorage", method = RequestMethod.POST)
    @Transactional
    public Result batPushStorageOmAppliancePurchase(@RequestBody List<OmAppliancePurchase> omAppliancePurchases) {
        Map<String, Object> m = new HashMap<>();
        if (!omAppliancePurchases.isEmpty()) {
            omAppliancePurchases.forEach(this::pushStorageOmAppliancePurchase);
        }
        return Result.ok();
    }


    @ApiOperation(value = "办公用品采购表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = OmAppliancePurchase.class, props = {}, remark = "办公用品采购表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = OmAppliancePurchase.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        omAppliancePurchaseService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @AuditLog(firstMenu = "办公平台", secondMenu = "办公用品", func = "processApprova", funcDesc = "用品采购入库流程", operType = OperType.UPDATE)
    @RequestMapping(value = "/processApprova", method = RequestMethod.POST)
    public Result processApprova(@RequestBody Map<String, Object> flowVars) {
        QueryWrapper<OmAppliancePurchase> qw = QueryTools.initQueryWrapper(OmAppliancePurchase.class, flowVars);
        IPage page = QueryTools.initPage(flowVars);
        this.omAppliancePurchaseService.processApprova(page, qw, flowVars);
        logger.debug("procInstId=====" + flowVars.get("procInstId"));
        return Result.ok();
    }

    @ApiOperation(value = "办公用品采购表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelOmAppliancePurchase(@RequestBody List<OmAppliancePurchase> omAppliancePurchases) {
        User user = LoginUtils.getCurrentUserInfo();
        if (omAppliancePurchases.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<OmAppliancePurchase> datasDb = omAppliancePurchaseService.listByIds(omAppliancePurchases.stream().map(i -> i.getId()).collect(Collectors.toList()));
        List<OmAppliancePurchase> can = new ArrayList<>();
        List<OmAppliancePurchase> no = new ArrayList<>();
        for (OmAppliancePurchase data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            omAppliancePurchaseService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }
        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "办公用品采购表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = OmAppliancePurchase.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(OmAppliancePurchase omAppliancePurchase) {
        OmAppliancePurchase data = (OmAppliancePurchase) omAppliancePurchaseService.getById(omAppliancePurchase);
        return Result.ok().setData(data);
    }

}
